package sub

import (
	"fmt"
	"quipus/cmd/qpc/sub"
	"quipus/internal/utils"
	v1pb "quipus/proto/gen/api/v1"
	"strings"

	"github.com/spf13/cobra"
)

var (
	name      string
	sourceIds []string
	gtype     string
	avatar    string
	tags      []string
	options   []string
)

func init() {
	sub.RegisterCommonFlags(granaryCmd)

	createCmd.PersistentFlags().StringVarP(&name, "name", "n", "", "granary name")
	createCmd.PersistentFlags().StringSliceVarP(&sourceIds, "source", "s", []string{}, "resource source id list")
	createCmd.PersistentFlags().StringSliceVar(&tags, "tag", []string{}, "granary tags")

	createCmd.PersistentFlags().StringVarP(&gtype, "type", "t", "", "granary type:Document, WebSite, WebDocument, BaiDuNetDisk")
	createCmd.PersistentFlags().StringVarP(&avatar, "avatar", "a", "", "granary avatar URL")
	createCmd.PersistentFlags().StringSliceVarP(&options, "option", "o", []string{}, "granary options")
	granaryCmd.AddCommand(createCmd)
}

var createCmd = &cobra.Command{
	Use:   "create",
	Short: "Run the cmd to create granaries",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := sub.NewGrpcConnect(sub.QpConfig.QPAddress)
		if e != nil {
			return e
		}

		if sourceIds == nil || len(sourceIds) == 0 {
			return fmt.Errorf("source is required")
		}

		var sources []string
		if gtype == "Document" {
			for _, v := range sourceIds {
				sources = append(sources, utils.ResourceUrnPrefix+v)
			}
		} else {
			sources = sourceIds
		}

		qclient := v1pb.NewGranaryServiceClient(qconn)
		ctxWithToken := sub.NewCtxWithToken(sub.QpConfig.Token)
		in := &v1pb.CreateGranaryRequest{Name: name, Sources: sources, Tags: tags, Avatar: avatar}

		if len(options) > 0 {
			ov := make(map[string]string)
			for _, v := range options {
				a := strings.Split(v, "=")
				if len(a) == 2 {
					ov[a[0]] = a[1]
				}
			}
			in.Options = ov
		}

		rsp, err := qclient.CreateGranary(ctxWithToken, in)
		if err != nil {
			return err
		}
		fmt.Print(rsp)
		return nil
	},
}
